#include "qtmaterialeventpool.h"
#include "qtmaterialripple.h"
#include "qtmaterialrippleoverlay.h"
#include <QDebug>

QtMaterialEventPool& QtMaterialEventPool::instance()
{
    static QtMaterialEventPool pool;
    return pool;
}

QtMaterialEventPool::QtMaterialEventPool(QObject* parent)
    : QObject(parent)
    , m_maxPoolSize(50)
    , m_totalAcquired(0)
    , m_totalReleased(0)
    , m_totalCreated(0)
{
}

QtMaterialEventPool::~QtMaterialEventPool()
{
    clear();
}

QtMaterialRipple* QtMaterialEventPool::acquireRipple(const QPoint& center, QtMaterialRippleOverlay* overlay)
{
    QMutexLocker locker(&m_mutex);
    m_totalAcquired++;

    QtMaterialRipple* ripple = nullptr;

    // 尝试从池中获取
    if (!m_ripplePool.isEmpty()) {
        ripple = m_ripplePool.takeLast();
        // 重置状态
        resetRipple(ripple);
        ripple->setCenter(center);
        if (overlay) {
            ripple->setOverlay(overlay);
        }
        qDebug() << "[EventPool] Reused Ripple from pool, pool size:" << m_ripplePool.size();
    } else {
        // 池中没有可用对象，创建新对象
        ripple = new QtMaterialRipple(center, overlay);
        m_totalCreated++;
        qDebug() << "[EventPool] Created new Ripple, total created:" << m_totalCreated;
    }

    return ripple;
}

void QtMaterialEventPool::releaseRipple(QtMaterialRipple* ripple)
{
    if (!ripple) {
        return;
    }

    QMutexLocker locker(&m_mutex);
    m_totalReleased++;

    // 检查池是否已满
    if (m_ripplePool.size() >= m_maxPoolSize) {
        // 池已满，直接删除
        delete ripple;
        qDebug() << "[EventPool] Ripple pool full, deleted object";
    } else {
        // 重置状态并放入池中
        resetRipple(ripple);
        m_ripplePool.append(ripple);
        qDebug() << "[EventPool] Returned Ripple to pool, pool size:" << m_ripplePool.size();
    }
}

QPropertyAnimation* QtMaterialEventPool::acquirePropertyAnimation(QObject* target, const QByteArray& propertyName)
{
    QMutexLocker locker(&m_mutex);
    m_totalAcquired++;

    QPropertyAnimation* animation = nullptr;

    // 尝试从池中获取
    if (!m_animationPool.isEmpty()) {
        animation = m_animationPool.takeLast();
        // 重置状态
        resetPropertyAnimation(animation);
        animation->setTargetObject(target);
        animation->setPropertyName(propertyName);
        qDebug() << "[EventPool] Reused PropertyAnimation from pool, pool size:" << m_animationPool.size();
    } else {
        // 池中没有可用对象，创建新对象
        animation = new QPropertyAnimation();
        animation->setTargetObject(target);
        animation->setPropertyName(propertyName);
        m_totalCreated++;
        qDebug() << "[EventPool] Created new PropertyAnimation, total created:" << m_totalCreated;
    }

    return animation;
}

void QtMaterialEventPool::releasePropertyAnimation(QPropertyAnimation* animation)
{
    if (!animation) {
        return;
    }

    QMutexLocker locker(&m_mutex);
    m_totalReleased++;

    // 检查池是否已满
    if (m_animationPool.size() >= m_maxPoolSize) {
        // 池已满，直接删除
        delete animation;
        qDebug() << "[EventPool] PropertyAnimation pool full, deleted object";
    } else {
        // 重置状态并放入池中
        resetPropertyAnimation(animation);
        m_animationPool.append(animation);
        qDebug() << "[EventPool] Returned PropertyAnimation to pool, pool size:" << m_animationPool.size();
    }
}

QGraphicsColorizeEffect* QtMaterialEventPool::acquireColorizeEffect()
{
    QMutexLocker locker(&m_mutex);
    m_totalAcquired++;

    QGraphicsColorizeEffect* effect = nullptr;

    // 尝试从池中获取
    if (!m_effectPool.isEmpty()) {
        effect = m_effectPool.takeLast();
        // 重置状态
        resetColorizeEffect(effect);
        qDebug() << "[EventPool] Reused ColorizeEffect from pool, pool size:" << m_effectPool.size();
    } else {
        // 池中没有可用对象，创建新对象
        effect = new QGraphicsColorizeEffect();
        m_totalCreated++;
        qDebug() << "[EventPool] Created new ColorizeEffect, total created:" << m_totalCreated;
    }

    return effect;
}

void QtMaterialEventPool::releaseColorizeEffect(QGraphicsColorizeEffect* effect)
{
    if (!effect) {
        return;
    }

    QMutexLocker locker(&m_mutex);
    m_totalReleased++;

    // 检查池是否已满
    if (m_effectPool.size() >= m_maxPoolSize) {
        // 池已满，直接删除
        delete effect;
        qDebug() << "[EventPool] ColorizeEffect pool full, deleted object";
    } else {
        // 重置状态并放入池中
        resetColorizeEffect(effect);
        m_effectPool.append(effect);
        qDebug() << "[EventPool] Returned ColorizeEffect to pool, pool size:" << m_effectPool.size();
    }
}

int QtMaterialEventPool::setMaxPoolSize(int maxSize)
{
    const int MIN_SIZE = 10;
    const int MAX_SIZE = 200;

    int newSize = qBound(MIN_SIZE, maxSize, MAX_SIZE);

    if (newSize != maxSize) {
        qWarning() << "[E040_INVALID_SIZE] Requested pool size" << maxSize
                   << "out of range, adjusted to" << newSize;
    }

    QMutexLocker locker(&m_mutex);
    m_maxPoolSize = newSize;

    // 如果池大小超过新上限，裁剪多余的对象
    while (m_ripplePool.size() > m_maxPoolSize) {
        QtMaterialRipple* ripple = m_ripplePool.takeLast();
        delete ripple;
    }

    while (m_animationPool.size() > m_maxPoolSize) {
        QPropertyAnimation* animation = m_animationPool.takeLast();
        delete animation;
    }

    while (m_effectPool.size() > m_maxPoolSize) {
        QGraphicsColorizeEffect* effect = m_effectPool.takeLast();
        delete effect;
    }

    qDebug() << "[EventPool] Max pool size set to" << m_maxPoolSize;
    return m_maxPoolSize;
}

QtMaterialEventPool::PoolStats QtMaterialEventPool::getStats() const
{
    QMutexLocker locker(&m_mutex);

    PoolStats stats;
    stats.rippleCount = m_ripplePool.size();
    stats.animationCount = m_animationPool.size();
    stats.effectCount = m_effectPool.size();
    stats.totalAcquired = m_totalAcquired;
    stats.totalReleased = m_totalReleased;
    stats.totalCreated = m_totalCreated;
    stats.maxPoolSize = m_maxPoolSize;

    return stats;
}

void QtMaterialEventPool::clear()
{
    QMutexLocker locker(&m_mutex);

    // 清空 Ripple 池
    for (QtMaterialRipple* ripple : m_ripplePool) {
        delete ripple;
    }
    m_ripplePool.clear();

    // 清空 PropertyAnimation 池
    for (QPropertyAnimation* animation : m_animationPool) {
        delete animation;
    }
    m_animationPool.clear();

    // 清空 ColorizeEffect 池
    for (QGraphicsColorizeEffect* effect : m_effectPool) {
        delete effect;
    }
    m_effectPool.clear();

    qDebug() << "[EventPool] All pools cleared";
}

void QtMaterialEventPool::resetRipple(QtMaterialRipple* ripple)
{
    if (!ripple) {
        return;
    }

    // 停止动画
    ripple->stop();

    // 重置状态
    ripple->setRadius(0);
    ripple->setOpacity(0);
    ripple->setColor(Qt::black);
    ripple->setOverlay(nullptr);

    // 断开所有连接（避免与旧对象的连接残留）
    disconnect(ripple, nullptr, nullptr, nullptr);
}

void QtMaterialEventPool::resetPropertyAnimation(QPropertyAnimation* animation)
{
    if (!animation) {
        return;
    }

    // 停止动画
    animation->stop();

    // 重置状态
    animation->setTargetObject(nullptr);
    animation->setPropertyName(QByteArray());
    animation->setStartValue(QVariant());
    animation->setEndValue(QVariant());
    animation->setDuration(250);  // 默认时长
    animation->setEasingCurve(QEasingCurve::Linear);

    // 断开所有连接
    disconnect(animation, nullptr, nullptr, nullptr);
}

void QtMaterialEventPool::resetColorizeEffect(QGraphicsColorizeEffect* effect)
{
    if (!effect) {
        return;
    }

    // 重置状态
    effect->setColor(Qt::white);
    effect->setStrength(0.0);
    effect->setEnabled(true);
}
